<?php

namespace App\Http\Controllers\Brand;

use App\Events\Share;
use App\Http\Controllers\BaseController;
use App\Models\BrandNotInterested;
use App\Models\FirmBrand;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class BrandController extends BaseController
{

    public function index(Request $request)
    {
        $param = $this->validate($request,[
            'firm_profession_id' => 'integer',
            'firm_category_id' => 'integer',
            'brand_location_id' => 'integer',
            'brand_cradle_id' => 'integer',
            'cooperation_area' => 'max:60',
            'keyword' => 'max:60',
            'rank_type' => 'in:1,2,3,4,5,6',
            'start_invest_amount' => 'numeric',
            'end_invest_amount' => 'numeric'
        ]);

        $query = FirmBrand::query()
                    ->selectRaw('*,(select count(id) from firm_brand_messages where brand_id=firm_brands.id) as join_count,
                    (select count(id) from user_like_brands where brand_id=firm_brands.id) as like_count,
                    (select sum(view_count) from firm_brand_browses where brand_id=firm_brands.id) as view_count,
                    (select count(user_id) from user_follows where status=1 and friend_id=firm_brands.user_id) as follow_count,
                     (select count(id) from user_collect_brands where status=1 and brand_id=firm_brands.id) as collect_count,
                     (select sum(share_count) from user_share_brands where brand_id=firm_brands.id) as share_count')
                    ->with('profile');

        if (isset($param['firm_profession_id'])){
            $query->where('firm_profession_id',$param['firm_profession_id']);
        }


        if (isset($param['firm_category_id'])){
            $query->where('firm_category_id',$param['firm_category_id']);
        }


        if (isset($param['brand_location_id'])){
            $query->where('brand_location_id',$param['brand_location_id']);
        }


        if (isset($param['brand_cradle_id'])){
            $query->where('brand_cradle_id',$param['brand_cradle_id']);
        }

        if (isset($param['rank_type'])){
            switch ($param['rank_type']){
                case 1 :
                    $query->orderByDesc('view_count');
                    break;
                case 2 :
                    $query->orderByDesc('like_count');
                    break;
                case 3 :
                    $query->orderByDesc('follow_count');
                    break;
                case 4 :
                    $query->orderByDesc('join_count');
                    break;
                case 5 :
                    $query->orderByDesc('collect_count');
                    break;
                case 6 :
                    $query->orderByDesc('share_count');
                    break;
            }
        }else{

            $query->orderByDesc('id');
        }



        if (isset($param['keyword'])){
            $query->where('name','like','%'.$param['keyword'].'%');
        }


        if (isset($param['cooperation_area'])){
            $cooperation_area = $param['cooperation_area'];
            $query->whereHas('profile',function ($q) use ($cooperation_area){
                $q->whereRaw("JSON_CONTAINS(cooperation_area,'[\"$cooperation_area\"]')");
            });
        }

        if (isset($param['start_invest_amount']) && isset($param['end_invest_amount'])){
            $start_invest_amount = $param['start_invest_amount'];
            $end_invest_amount = $param['end_invest_amount'];
            $query->whereHas('profile',function ($q) use ($start_invest_amount,$end_invest_amount){
                $q->where('start_invest_amount','>=',$start_invest_amount)->where('end_invest_amount','<=',$end_invest_amount);
            });
        }


        if (isset($param['firm_category_id'])){
            $query->where('firm_category_id',$param['firm_category_id']);
        }


        $profiles = $query->whereNotExists(function ($q){
            $user_id = auth('api')->id();
            $q->select(DB::raw(1))
                ->from('brand_not_interesteds')
                ->where('user_id',$user_id)
                ->whereColumn('brand_not_interesteds.brand_id','firm_brands.id');
        })->where('audit_status',2)->simplePaginate();

        return $this->success($profiles);
    }


    public function firm(Request $request)
    {
        $param = $this->validate($request,[
            'firm_id' => 'required',
        ]);

        $profiles = FirmBrand::query()
                    ->where('firm_id',$param['firm_id'])
                    ->with('profile')->get();

        return $this->success($profiles);
    }



    public function share(Request $request)
    {
        $param = $this->validate($request,[
            'brand_id' => 'required|integer'
        ]);

        $user_id = auth('api')->id();
        $share_id  = DB::table('user_share_brands')
            ->where('user_id',$user_id)
            ->where('brand_id',$param['brand_id'])
            ->whereDate('share_time',date('Y-m-d'))
            ->value('id');

        if (!$share_id){
            $result = DB::table('user_share_brands')->insert([
                'user_id' => $user_id,
                'brand_id' => $param['brand_id'],
                'share_count' => 1,
                'share_time' => date('Y-m-d H:i:s')
            ]);
        }else{
            $result = DB::table('user_share_brands')
                ->where('id',$share_id)
                ->increment('brand_id');
        }

        event(new Share($user_id));

        return $result ? $this->success() : $this->error();
    }


    public function show($id)
    {

        $user_id = auth('api')->id();
        $profile = FirmBrand::query()
                        ->selectRaw('firm_brands.*,(select sum(view_count) from firm_brand_browses where brand_id=firm_brands.id) as view_count,
                        (select count(id) from firm_brand_messages where brand_id=firm_brands.id) as join_count')
                        ->withCount(['gift' => function($q){
                            $q->where('status',1);
                        }])->with(['profile','gift' => function($q){
                            $q->with('user:id,avatar,nickname')->where('status',1)->limit(10);
                        }])->withCount(['follow as is_follow' => function($q) use ($user_id){
                            $q->where('user_id',$user_id)->where('status',1);
                        }])->withCount(['like as is_like' => function($q) use ($user_id){
                            $q->where('user_id',$user_id)->where('status',1);
                        }])->withCount(['collect as is_collect' => function($q) use ($user_id){
                            $q->where('user_id',$user_id)->where('status',1);
                        }])->where('id',$id)
                        ->first();

        $browse_id =  DB::table('firm_brand_browses')
            ->whereDate('view_time',date('Y-m-d'))
            ->where('user_id',$user_id)
            ->where('brand_id',$id)
            ->value('id');

        if (!$browse_id){
            DB::table('firm_brand_browses')
                ->insert([
                    'brand_id' => $id,
                    'user_id' => $user_id,
                    'view_count' => 1,
                    'view_time' => date('Y-m-d H:i:s')
                ]);
        }else{
            DB::table('firm_brand_browses')->where('id',$browse_id)->increment('view_count');
        }


        return $this->success($profile);
    }

    public function interested(Request $request)
    {
        $param = $this->validate($request,[
            'brand_id' => 'required|integer'
        ]);
        $param['user_id'] = auth('api')->id();
        $model =  BrandNotInterested::query()->create($param);

        if ($model->getKey()){
            return $this->success('请求成功');
        }
        return $this->success('请求失败');
    }

    public function store(Request $request)
    {
        $param = $this->validate($request,[
            'firm_id' => 'required',
            'name' => 'required',
            'firm_profession_id' => 'required',
            'brand_cradle_id' => 'required',
            'brand_location_id' => 'required',
            'certificate' => 'string',
        ]);

        $param['user_id'] = auth('api')->id();
        $brand = FirmBrand::query()->create($param);


        return $brand->getKey() ? $this->success() : $this->error();
    }


}
